#!/usr/bin/env node

import { readFileSync, writeFileSync } from 'fs';
import { join } from 'path';

const PACKAGES = [
  'iframe-communicator',
  'vite-plugin-iframe-communicator',
  'webpack-plugin-iframe-communicator'
];

const PACKAGES_DIR = 'packages';

function bumpVersion(version, type = 'patch') {
  const [major, minor, patch] = version.split('.').map(Number);
  
  switch (type) {
    case 'major':
      return `${major + 1}.0.0`;
    case 'minor':
      return `${major}.${minor + 1}.0`;
    case 'patch':
    default:
      return `${major}.${minor}.${patch + 1}`;
  }
}

function updatePackageVersion(packageName, newVersion) {
  const packagePath = join(PACKAGES_DIR, packageName, 'package.json');
  const packageJson = JSON.parse(readFileSync(packagePath, 'utf8'));
  
  console.log(`📦 ${packageName}: ${packageJson.version} → ${newVersion}`);
  
  packageJson.version = newVersion;
  
  // 更新依赖中的 workspace 依赖
  if (packageJson.dependencies) {
    Object.keys(packageJson.dependencies).forEach(dep => {
      if (dep === 'iframe-communicator' && packageJson.dependencies[dep] === 'workspace:*') {
        // workspace:* 保持不变，不需要更新
      }
    });
  }
  
  writeFileSync(packagePath, JSON.stringify(packageJson, null, 2) + '\n');
}

function main() {
  const args = process.argv.slice(2);
  const versionType = args[0] || 'patch';
  const targetVersion = args[1]; // 可选：直接指定版本号
  
  if (!['patch', 'minor', 'major'].includes(versionType) && !targetVersion) {
    console.error('Usage: node scripts/bump-versions.js [patch|minor|major] [version]');
    process.exit(1);
  }
  
  console.log('🚀 开始升级版本号...\n');
  
  // 获取第一个包的当前版本作为基准
  const firstPackagePath = join(PACKAGES_DIR, PACKAGES[0], 'package.json');
  const firstPackage = JSON.parse(readFileSync(firstPackagePath, 'utf8'));
  const currentVersion = firstPackage.version;
  
  let newVersion;
  if (targetVersion) {
    newVersion = targetVersion;
    console.log(`📍 指定版本号: ${newVersion}`);
  } else {
    newVersion = bumpVersion(currentVersion, versionType);
    console.log(`📍 升级类型: ${versionType}`);
    console.log(`📍 当前版本: ${currentVersion} → 新版本: ${newVersion}\n`);
  }
  
  // 更新所有包的版本号
  PACKAGES.forEach(packageName => {
    updatePackageVersion(packageName, newVersion);
  });
  
  console.log('\n✅ 版本号升级完成！');
  console.log('\n下一步操作：');
  console.log('1. 运行 `pnpm install` 更新 lock 文件');
  console.log('2. 运行 `git add . && git commit -m "chore: bump version to ${newVersion}"`');
  console.log('3. 运行 `pnpm -r publish` 发布所有包');
}

main();